package cn.matezk.things.broker.hook;

import io.grpc.Server;
import io.grpc.ServerBuilder;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class ExHookServer {

    @Autowired
    private HookProvider hookProvider;

    @Value("${mqtt.hook.port}")
    private Integer port;

    private Server server;

    @PostConstruct
    public void start() throws InterruptedException {
        new Thread(() -> {
            try {
                init();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }).start();
        blockUntilShutdown();
    }

    public void init() throws IOException {
        server = ServerBuilder.forPort(port)
                .addService(hookProvider)
                .build().start();
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            try {
                ExHookServer.this.stop();
            } catch (InterruptedException e) {
                log.error(e.getMessage());
            }
        }));
    }
    private void stop() throws InterruptedException {
        if (server != null) {
            server.shutdown().awaitTermination(30, TimeUnit.SECONDS);
        }
    }

    private void blockUntilShutdown() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();
        }
    }
}
